from DrissionPage import ChromiumPage
import requests
import re
import os


# 单个



if not os.path.exists('video'):
    os.mkdir('video')
if not os.path.exists('img'):
    os.mkdir('img')
if not os.path.exists('cover'):
    os.mkdir('cover')
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0',
    'referer': 'https://www.douyin.com'
}

img_c = 1
url = input('输入链接：')
url = re.findall(' http(.*?) ', url)[0]
url = 'http' + url
print(url)
dp = ChromiumPage()
# url = 'https://www.douyin.com/user/MS4wLjABAAAAKmhsjiGavu1iTPBLYKD0-m9P-3LG1cJkNrFhaO-JgrnfTbqrgSw66hrf26se_eHC?showSubTab=video&showTab=post'
# url = 'https://www.douyin.com/user/MS4wLjABAAAAKmhsjiGavu1iTPBLYKD0-m9P-3LG1cJkNrFhaO-JgrnfTbqrgSw66hrf26se_eHC'
dp.listen.start('aweme/v1/web/aweme/detail/?device_platform')
dp.get(url)
print('======================================')
r = dp.listen.wait()
js = r.response.body
ad = js['aweme_detail']
# 图片
try:
    images_url = ad['images']
    for image in images_url:
        images_url = image['url_list'][-1]
        print('======================================')
        print(images_url)
        print('======================================')
        images_res = requests.get(images_url, headers=headers)
        with open(f'img/{img_c}.jpeg', 'wb') as f:
            f.write(images_res.content)
        img_c += 1
except:
    print('======================================')
    print('没有图片')
    pass
# 文案
desc = ad['desc']
# 视频
video_url = ad['video']['play_addr']['url_list'][-1]
comment_gid = ad['comment_gid']
print('======================================')
print(desc)
print(comment_gid)
print(video_url)
print('======================================')
# 封面图片
cover_url = ad['video']['cover']['url_list'][0]
cover_res = requests.get(cover_url, headers=headers)
with open(f'cover/cover-{comment_gid}.jpeg', 'wb') as f:
    f.write(cover_res.content)
video_res = requests.get(video_url, headers=headers)
with open(f'video/{comment_gid}.mp4', 'wb') as f:
    f.write(video_res.content)
print('下载完成')





# https://www.douyin.com/user/MS4wLjABAAAAq2NP4D-ZN0fRua--dom-MZBSVwXx0u3-HeNEuxe8vSA

